/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.condition;

import javax.servlet.http.HttpServletRequest;

/**name: 有值；value: 无值；isNegated: false：参数存在匹配
 * <br/>name: 有值；value: 无值；isNegated: true：参数不存在匹配
 * <br/>name: 有值；value: 有值；isNegated: false：参数值匹配
 * <br/>name: 有值；value: 有值；isNegated: true：参数值不匹配
 * <br/>Supports "name=value" style expressions as described in:
 * {@link org.springframework.web.bind.annotation.RequestMapping#params()} and
 * {@link org.springframework.web.bind.annotation.RequestMapping#headers()}.
 *
 * @author Rossen Stoyanchev
 * @author Arjen Poutsma
 * @since 3.1
 */
abstract class AbstractNameValueExpression<T> implements NameValueExpression<T> {

	/**保存参数表达式中的参数名
	 */
	protected final String name;

	/**保存参数表达式中的参数值，可以为空
	 */
	protected final T value;

	/**是否是反向匹配
	 */
	protected final boolean isNegated;


	/**构造时解析表达式
	 * @param expression
	 */
	AbstractNameValueExpression(String expression) {
		// 表达式字符串中等号位置
		int separator = expression.indexOf('=');
		// 为-1表示不存在等号，进入解析无参数值的逻辑
		if (separator == -1) {
			// 如果第一个字符为！，表示为反向匹配逻辑
			this.isNegated = expression.startsWith("!");
			// 解析表达式中的参数名
			this.name = (this.isNegated ? expression.substring(1) : expression);
			// 无value
			this.value = null;
		}
		else {
			// 存在等号，进入解析参数名与参数值逻辑
			// 判断等号前一个字符是否是！，是则为反向匹配
			this.isNegated = (separator > 0) && (expression.charAt(separator - 1) == '!');
			// 解析参数名部分
			this.name = (this.isNegated ? expression.substring(0, separator - 1) : expression.substring(0, separator));
			// 解析参数值部分
			this.value = parseValue(expression.substring(separator + 1));
		}
	}


	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public T getValue() {
		return this.value;
	}

	@Override
	public boolean isNegated() {
		return this.isNegated;
	}

	public final boolean match(HttpServletRequest request) {
		boolean isMatch;
		// 如果value不为空，则为参数值匹配逻辑，执行匹配参数值方法，拿到匹配结果
		if (this.value != null) {
			isMatch = matchValue(request);
		}
		else {
			// 否则为参数存在匹配，执行参数名匹配逻辑，获取结果
			isMatch = matchName(request);
		}
		// 如果是反向，则对匹配结果执行否运算
		return (this.isNegated ? !isMatch : isMatch);
	}


	protected abstract boolean isCaseSensitiveName();

	protected abstract T parseValue(String valueExpression);

	protected abstract boolean matchName(HttpServletRequest request);

	protected abstract boolean matchValue(HttpServletRequest request);


	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj instanceof AbstractNameValueExpression) {
			AbstractNameValueExpression<?> other = (AbstractNameValueExpression<?>) obj;
			// 如果名字区分大小写，则使用name；否则，使用name的小写形式，最终name比较使用thisName和otherName
			String thisName = (isCaseSensitiveName() ? this.name : this.name.toLowerCase());
			String otherName = (isCaseSensitiveName() ? other.name : other.name.toLowerCase());
			// 分别比较name、value、isNegated的值，如果都相等，则视为表达式相同，这里有一个bug: equalsIgnoreCase，导致不管是否区分大小写，这里都使用忽略大小写比较，
			// 当区分大小写时，会导致hashCode值不相等，但equals值相等，不符合java规范
			return (thisName.equalsIgnoreCase(otherName) &&
					(this.value != null ? this.value.equals(other.value) : other.value == null) &&
					this.isNegated == other.isNegated);
		}
		return false;
	}

	@Override
	public int hashCode() {
		// 计算hashCode大小，保证在区分大小写时，大小写不同的name取到的hashCode不相同；在不区分大小写时，大小写不同的name取到的hashCode相同
		int result = (isCaseSensitiveName() ? this.name.hashCode() : this.name.toLowerCase().hashCode());
		result = 31 * result + (this.value != null ? this.value.hashCode() : 0);
		result = 31 * result + (this.isNegated ? 1 : 0);
		return result;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		if (this.value != null) {
			builder.append(this.name);
			if (this.isNegated) {
				builder.append('!');
			}
			builder.append('=');
			builder.append(this.value);
		}
		else {
			if (this.isNegated) {
				builder.append('!');
			}
			builder.append(this.name);
		}
		return builder.toString();
	}

}
